<script setup lang="ts">
import { useGoodsStore } from "@/stores/goodsStore";
const goodsStore = useGoodsStore();
const { mainPictures } = storeToRefs(goodsStore);

const current = ref(0);

// 声明布尔值变量  记录鼠标是否入了中图
// 如果鼠标入到了中图  布尔值变true 出中图 为false
// 根据该布尔值决定是否渲染中图的镜片和大图
// 获取中图容器
const target = ref();
// isOutside 表示鼠标是否移出 如果移出为 true 或 false
const { isOutside, elementX, elementY } = useMouseInElement(target);

let layerPosition = reactive({ left: 0, top: 0 });
// 用于记录大图位置
const bgPosition = reactive({ x: 0, y: 0 });
watchEffect(() => {
  layerPosition.left = elementX.value - 100;
  layerPosition.top = elementY.value - 100;
  if (layerPosition.left < 0) {
    layerPosition.left = 0;
  } else if (layerPosition.left > 200) {
    layerPosition.left = 200;
  }
  if (layerPosition.top < 0) {
    layerPosition.top = 0;
  } else if (layerPosition.top > 200) {
    layerPosition.top = 200;
  }
  // 记录大图位置
  bgPosition.x = -layerPosition.left * 2;
  bgPosition.y = -layerPosition.top * 2;
});
</script>
<template>
  <div class="goods-image">
    <div
      class="large"
      v-show="!isOutside"
      :style="{
        backgroundImage: `url(${mainPictures[current]})`,
        backgroundPositionX: bgPosition.x + 'px',
        backgroundPositionY: bgPosition.y + 'px',
      }"
    ></div>
    <div class="middle" ref="target">
      <img :src="mainPictures[current]" alt="" />
      <div
        class="layer"
        v-show="!isOutside"
        :style="{
          left: layerPosition.left + 'px',
          top: layerPosition.top + 'px',
        }"
      ></div>
    </div>
    <ul class="small">
      <li
        v-for="(picture, index) in mainPictures"
        :key="picture"
        :class="{ active: current === index }"
        @mouseenter="current = index"
      >
        <img :src="picture" alt="" />
      </li>
    </ul>
  </div>
</template>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
}
</style>
